package com.heima.comment.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.constants.CommentConstants;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.*;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author JianKang
 * @create 2023-11-06 14:03
 */
@Service
@Slf4j
@Transactional
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.校验参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.查询父评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "评论不存在");
        }
        //4.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    public void saveWmCommentRepay(WmUser wmUser, String commentId, String content) {
        //1.校验参数
        if (commentId == null || wmUser == null || wmUser.getApUserId() == null || StringUtils.isBlank(content)) {
            return;
        }

        //3.查询父评论
        ApComment apComment = mongoTemplate.findById(commentId, ApComment.class);
        if (apComment == null) {
            return;
        }
        //4.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(Integer.valueOf(wmUser.getApUserId()));
        apCommentRepay.setAuthorName(wmUser.getName());
        apCommentRepay.setCommentId(commentId);
        apCommentRepay.setContent(content);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);
    }

    @Override
    public void commentLike(WmUser wmUser, String commentId, Short operation) {
        //1.校验参数
        if (wmUser == null || wmUser.getApUserId() == null || commentId == null || operation == null) {
            return ;
        }

        //4.是否是点赞
        //4.1点赞
        if (operation.equals(CommentConstants.COMMENT_LIKE)) {
            ApCommentLike apCommentLike = new ApCommentLike();

            apCommentLike.setAuthorId(wmUser.getApUserId());
            apCommentLike.setCommentId(commentId);
            apCommentLike.setOperation(CommentConstants.COMMENT_LIKE);
            mongoTemplate.save(apCommentLike);
        } else {
            //4.2取消点赞
            Query query = Query.query(Criteria.where("authorId").is(wmUser.getApUserId()).and("commentId").is(commentId));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
    }

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.校验参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.校验登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询评论
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(20);
        List<CommentRepayVo> commentRepayVos = mongoTemplate.find(query, ApCommentRepay.class).stream().map(apCommentRepay -> {
            CommentRepayVo commentRepayVo = new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, commentRepayVo);

            //查询用户是否点赞
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
            if (apCommentRepayLike != null) {
                commentRepayVo.setOperation((short) 0);
            } else {
                commentRepayVo.setOperation((short) 1);
            }
            return commentRepayVo;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(commentRepayVos);
    }

    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto dto) {
        //1.校验参数
        if (dto == null || dto.getCommentRepayId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.查询评论
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "评论不存在");
        }
        //4.是否是点赞
        //4.1点赞
        if (dto.getOperation().equals(CommentConstants.COMMENT_LIKE)) {
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //4.2取消点赞
            Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delCommentRepay(String commentRepayId) {
        if (commentRepayId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(commentRepayId, ApCommentRepay.class);
        if (apCommentRepay != null) {
            mongoTemplate.remove(apCommentRepay);
            ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
